
const path = require('path')
const fs = require('fs')
// const fs = require('fs')
const cp = require('child_process')
let bookmarksDataCache = null
var md5 = require('md5');

// var config={
//   web:"utools",
//   dir:['C:\\Users\\jike.xue\\OneDrive - Csisolar'],
//   exeDir:[]
// }
let config = {
  web: "",
  dir: [],
  exeDir: []
};
loadConfig();
function loadConfig(){
  const configStr = utools.dbStorage.getItem('config');
  if (configStr){
    config=JSON.parse(configStr);
  }else{
    utools.dbStorage.setItem('config',JSON.stringify(config))
  }
}

function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
function getBookmarks (dataDir, browser) {
  const profiles = ['Default', 'Profile 3', 'Profile 2', 'Profile 1']
  const profile = profiles.find(profile => fs.existsSync(path.join(dataDir, profile, 'Bookmarks')))
  if (!profile) return []
  const bookmarkPath = path.join(dataDir, profile, 'Bookmarks')
  const bookmarksData = []
  const icon = browser + '.png'
  try {
    const data = JSON.parse(fs.readFileSync(bookmarkPath, 'utf-8'))
    const getUrlData = (item, folder) => {
      if (!item || !Array.isArray(item.children)) return
      item.children.forEach(c => {
        if (c.type === 'url') {
          bookmarksData.push({
            addAt: parseInt(c.date_added),
            title: c.name || '',
            description: (folder ? '「' + folder + '」' : '') + c.url,
            url: c.url,
            folder:folder,
            browser,
            icon
          })
        } else if (c.type === 'folder') {
          getUrlData(c, folder ? folder + ' - ' + c.name : c.name)
        }
      })
    }
    getUrlData(data.roots.bookmark_bar, '')
    getUrlData(data.roots.other, '')
    getUrlData(data.roots.synced, '')
  } catch (e) {}
  return bookmarksData
}

function openUrlByChrome (url) {
  if (process.platform === 'win32') {
    const suffix = `${path.sep}Google${path.sep}Chrome${path.sep}Application${path.sep}chrome.exe`
    const prefixes = [process.env['PROGRAMFILES(X86)'], process.env.PROGRAMFILES, process.env.LOCALAPPDATA].filter(Boolean)
    const prefix = prefixes.find(prefix => fs.existsSync(path.join(prefix, suffix)))
    const chromeApp = path.join(prefix, suffix)
    if (chromeApp) {
      cp.spawn(chromeApp, [url], { detached: true })
    } else {
      window.utools.shellOpenExternal(url)
    }
    return
  }
  if (process.platform === 'darwin') {
    const chromeApp = '/Applications/Google Chrome.app'
    if (fs.existsSync(chromeApp)) {
      cp.spawn('open', ['-a', chromeApp, url], { detached: true })
    } else {
      window.utools.shellOpenExternal(url)
    }
  }
}

function openUrlByEdge (url) {
  if (process.platform === 'win32') {
    const args = ['shell:AppsFolder\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge']
    args.push(url)
    cp.spawn('start', args, { shell: 'cmd.exe', detached: true }).once('error', () => {
      window.utools.shellOpenExternal(url)
    })
    return
  }
  if (process.platform === 'darwin') {
    const edgeApp = '/Applications/Microsoft Edge.app'
    if (fs.existsSync(edgeApp)) {
      cp.spawn('open', ['-a', edgeApp, url], { detached: true })
    } else {
      window.utools.shellOpenExternal(url)
    }
  }
}


function getWindow(){
  if (window==null){
    return {
      exports:{}
    };
  }
  return window;
}
function runAction(call){
  if (window==null){
    call();
  }else{
    window.utools.hideMainWindow()
    call();
    window.utools.outPlugin()
  }

}

function init(){
  bookmarksDataCache = []
  let chromeDataDir
  let edgeDataDir
  if (process.platform === 'win32') {
    chromeDataDir = path.join(process.env.LOCALAPPDATA, 'Google/Chrome/User Data')
    edgeDataDir = path.join(process.env.LOCALAPPDATA, 'Microsoft/Edge/User Data')
  } else if (process.platform === 'darwin') {
    chromeDataDir = path.join(window.utools.getPath('appData'), 'Google/Chrome')
    edgeDataDir = path.join(window.utools.getPath('appData'), 'Microsoft Edge')
  } else { return }
  if (fs.existsSync(chromeDataDir)) {
    bookmarksDataCache.push(...getBookmarks(chromeDataDir, 'chrome'))
  }
  if (fs.existsSync(edgeDataDir)) {
    bookmarksDataCache.push(...getBookmarks(edgeDataDir, 'edge'))
  }
  if (bookmarksDataCache.length > 0) {
    bookmarksDataCache = bookmarksDataCache.sort((a, b) => a.addAt - b.addAt)
  }
}
function loadFeature(){
  loadConfig();
  init();
  const actionMap={};
  bookmarksDataCache.forEach(it=>{
    if (it.folder==config.web){
      it['action']= 'web'

      actionMap[`${it.action}${it.url}`]=it;
    }
  })

  config.dir.forEach(dir=>{
    var subDir = fs.readdirSync(dir);
    // console.log(subDir)
    subDir.forEach(it=>{
      var url = path.join(dir,it);
      var stats = fs.lstatSync(url);
      if (stats.isDirectory()){

        actionMap[`dir_${url}`]={
          title:it,
          url:url,
          action:'dir',
          icon:'dir.png'
        }
      }
    })

  })


  console.log(actionMap)
  const  action={};
  for (const key in actionMap) {
    // console.log(key)
    const data= actionMap[key]
    action[key]={
      mode:'none',
      args: {
        // 进入插件应用时调用
        enter: (action) => {
          runAction(()=>{
            if (data.action=='web'){
              utools.shellOpenExternal(data.url)
            }else if (data.action=='dir'){
              utools.shellOpenPath(data.url)
            }
          })
        }
      }
    }

    window.utools.setFeature({
      "code": key,
      "explain": `${data.title}(${key})--01`,
      "icon": data.icon,
      // "icon": "...",
      // "platform": ["win32", "darwin", "linux"]
      "cmds": [data.title]
    })

  }

  utools.showNotification("加载成功");

  getWindow().exports = {
    "ktools_config": ktoolsConfig,
    ...action
  };
}

// loadFeature();
// console.log(bookmarksDataCache)

function clearFeature() {
  const features = utools.getFeatures()
  features.forEach(it => {
    if ('ktools_config'==it.code){
      return;
    }
    utools.removeFeature(it.code)
  })
  utools.showNotification("已清空");
}
// clearFeature();
// getWindow().
ktoolsConfig={
  mode: 'list',
  args: {
    // 进入插件应用时调用
    // 进入插件应用时调用（可选）
    enter: (action, callbackSetList) => {
      // 如果进入插件应用就要显示列表数据
      callbackSetList([
        {
          title: '重载',
          description: '',
          icon:'' // 图标(可选)
        }
      ])
    },
    // 子输入框内容变化时被调用 可选 (未设置则无搜索)
    search: (action, searchWord, callbackSetList) => {
      // 获取一些数据
      // 执行 callbackSetList 显示出来
      callbackSetList([
        {
          title: '重载',
          description: '',
          icon:'', // 图标
        },
        {
          title: '添加文件夹',
          description: searchWord,
          icon:'', // 图标
        },
        {
          title: '设置收藏夹',
          description: searchWord,
          icon:'', // 图标
        },
      ])
    },
    // 用户选择列表中某个条目时被调用
    select: (action, itemData, callbackSetList) => {
      window.utools.hideMainWindow()
      // const url = itemData.url
      var config = JSON.parse(utools.dbStorage.getItem("config"));
      if (itemData.title=='添加文件夹'){
        config.dir.push(itemData.description)
      }
      if (itemData.title=='设置收藏夹'){
        config.web=itemData.description
      }
      if (itemData.title=='重载')
      {
        clearFeature();
        loadFeature();
      }
      utools.dbStorage.setItem("config",JSON.stringify(config))

      window.utools.outPlugin()
    },
    // 子输入框为空时的占位符，默认为字符串"搜索"
    placeholder: "配置"


  }
};
window.exports  = {

  "ktools_config": ktoolsConfig

};
